package longrise.phone.com.bjjt_jyb.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.widget.AlertDialogRecord;
import longrise.phone.com.bjjt_jyb.widget.PicModule;

/**
 * Created by Administrator on 2016/7/13.
 */
public class RecordViewManager{

    private Context context;

    private View view;

    private ImageView mPlayIV;//播放按钮

    private Button mRecordBtn;//录音按钮

    private String recordPath;

    private float eventY;// 手指滑动的Y坐标

    private RecordHelper recordHelper;// 录音帮助类

    private AnimationDrawable anim;//录音播放动画

    private PopupWindow recordPopWindow;//录音的悬浮框

    private TextView recordTextView;//录音的提示语

    private Boolean startRecord = false;
    private ImageView record_iv_record;
    private AlertDialogRecord alertDialogRecord;
    private PicModule pm_record;

    public RecordViewManager(Context context, View view) {
        this.context = context;
        this.view = view;
        initViews(view);
    }

    private void initViews(View view) {
        pm_record = (PicModule) view.findViewById(R.id.pm_record);//录制图片
        record_iv_record = pm_record.getIv_record();//录制图片
        mPlayIV = pm_record.getIv_recordplay();//播放图片
        mRecordBtn = pm_record.getBt_record();//重新录制
        record_iv_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    mPlayIV.setVisibility(View.GONE);
                    if (null!=recordHelper&&recordHelper.isPlaying()) {
                        recordHelper.stopMPlayer();
                    }
                    mRecordBtn.setText("最多可录120S");
                    //mRecordBtn.setBackgroundResource(R.drawable.record_btn_highlight_bg);
                    String recordPath = getDataFilePath(".mp3");
                    if (recordPath != null) {
                        File file = new File(recordPath).getParentFile();
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        if (recordHelper == null) {
                            initRecord();
                        }
                        recordHelper.startRecord(recordPath);
                        showRecordPopWindow();
                    } else {
                        Toast.makeText(context, "内存卡不存在或已损坏！", Toast.LENGTH_SHORT).show();
                    }
                    startRecord = true;

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mPlayIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (recordHelper == null) {
                    initRecord();
                }
                if (!recordHelper.isPlaying()) {
                    showPlayAnim();
                }
                recordHelper.playRecord(recordPath);
            }
        });

        if (mPlayIV == null || mRecordBtn == null) {
            return;
        }
        if (TextUtils.isEmpty(recordPath)) {
            mPlayIV.setVisibility(View.GONE);
        }else {//录音完成，将播放图像显示
            mPlayIV.setVisibility(View.VISIBLE);
        }
    }

    public recordOver getMyRecordOver() {
        return myRecordOver;
    }

    public void setMyRecordOver(recordOver myRecordOver) {
        this.myRecordOver = myRecordOver;
    }

    private recordOver myRecordOver;

    public interface recordOver {
        void onRecordOver();
    }

    // 实例化录音帮助类
    private void initRecord() {
        recordHelper = RecordHelper.getInstance(context);
        recordHelper.setMyRecordBtn(mRecordBtn);
        recordHelper.setmRecordOver(myRecordOver);
        recordHelper.setMyPlayIV(mPlayIV);
        recordHelper.setMyrecord_iv_record(record_iv_record);
        recordHelper.setOnRecordFinishListener(new RecordHelper.onRecordFinishListener() {
            @Override
            public void recordFinish(int time, String path) {
                closeRecordPopWindow();
                if (eventY < 0 || time < 2) {
                    new File(path).delete();
                    if (time < 2) {
                        Toast.makeText(context, "录音时间太短!", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                if (!TextUtils.isEmpty(path)) {
                    recordPath = path;
                    mPlayIV.setVisibility(View.VISIBLE);
                }
            }
        });
        recordHelper.setOnPlayFinishListener(new RecordHelper.onPlayFinishListener() {
            @Override
            public void playFinish() {
                // ֹͣ停止播放动画
                if (anim != null) {
                    anim.stop();
                }
                mPlayIV.setImageResource(R.mipmap.sound1);
            }
        });
    }

    /**
     * 显示播放的动画效果
     */
    private void showPlayAnim() {
        mPlayIV.setImageResource(R.drawable.record_voice_playanim);
        anim = (AnimationDrawable) mPlayIV.getDrawable();
        anim.start();
    }

    /**
     * 显示录音的悬浮框
     */
    private void showRecordPopWindow() throws Exception {
       /* View mView = LayoutInflater.from(context).inflate(
                R.layout.pub_popwindow_record, null);
        recordTextView = (TextView) mView.findViewById(R.id.public_popup_text);
        // LinearLayout public_popup_bar = (LinearLayout) mView.findViewById(R.id.public_popup_bar);
        TextView public_popup_text = (TextView) mView.findViewById(R.id.public_popup_text);
        public_popup_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recordHelper.finishRecord();
            }
        });
        recordPopWindow = new PopupWindow(mView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        recordPopWindow.showAtLocation(((Activity) context).getWindow().getDecorView(),
                Gravity.CENTER, 0, 0);
        recordPopWindow.setFocusable(true);*/

        alertDialogRecord = new AlertDialogRecord(context).builder();
        alertDialogRecord.setRecordOver(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recordHelper.finishRecord();
            }
        });
        alertDialogRecord.show();

    }

    /**
     * 关闭录音的悬浮框
     */
    private void closeRecordPopWindow() {
       /* if (null != recordPopWindow && recordPopWindow.isShowing()) {
            recordPopWindow.setFocusable(false);
            recordPopWindow.dismiss();
        }
        recordPopWindow = null;*/
        if(null!=alertDialogRecord){
            alertDialogRecord.dismiss();
        }
        alertDialogRecord=null;
    }

    /**
     * 显示录音的提示信息
     */
    public void showRecordToast(boolean isSave) {
        if (isSave) {
            recordTextView.setText("手指上滑，取消保存");
            recordTextView.setBackgroundColor((Color.parseColor("#d3d3d3")));
        } else {
            recordTextView.setText("松开手指，取消保存");
            recordTextView.setBackgroundColor(Color.RED);
        }
    }

    public String getRecordPath() {
        return recordPath;
    }

    /**
     * 获取录音文件的本地路径
     */
    public String getDataFilePath(String fileSuffix) {
        if (!Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return null;
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(Environment.getExternalStorageDirectory());
        buffer.append("/");
        buffer.append("hnjyb_record");
        buffer.append("/");
        buffer.append("data");
        buffer.append("/");
        buffer.append(System.currentTimeMillis());
        if (!TextUtils.isEmpty(fileSuffix)) {
            buffer.append(fileSuffix);
        }

        return buffer.toString();
    }
}
